package com.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.common.R;
import com.dto.DishDto;
import com.entity.Category;
import com.entity.Dish;
import com.entity.DishFlavor;
import com.service.CategoryService;
import com.service.DishFlavorService;
import com.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.digester.ArrayStack;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;
    //添加菜品
    @PostMapping
    @CacheEvict(value = "dishCache",allEntries = true)
    public R<String> addDish(@RequestBody DishDto dishDto){
        log.info("添加菜品为："+dishDto);
        dishService.saveWithFlavor(dishDto);
//        //操作后，写上到该类型菜品缓存在数据中的key
//        String key="dish_"+dishDto.getCategoryId()+"_1";
//        //删除缓存
//        redisTemplate.delete(key);
        return R.success("新增菜品成功");
    }
    //菜品分页查询
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        //查找菜品信息（除菜品类别名以外）
        Page<Dish> pageInfo=new Page(page,pageSize);
        //含有分类名称的一个封装对象
        Page<DishDto> pageDto=new Page();
        LambdaQueryWrapper<Dish> lqw=new LambdaQueryWrapper<>();
        lqw.eq(name!=null,Dish::getName,name);
        lqw.orderByDesc(Dish::getUpdateTime);
        dishService.page(pageInfo, lqw);
        int i=0;
        for (Dish record : pageInfo.getRecords()) {
            i++;
            System.out.println(i+"啦啦啦啦啦啦啦啦啦啦啦啦啦"+record.toString());
        }

        //pageinfo以及自动封装好对象，现在进行对象拷贝
        BeanUtils.copyProperties(pageInfo,pageDto,"records");//除了records属性以外，拷贝其他属性
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> dtoList=new ArrayList<>();
        for (Dish dish:records){
            DishDto dishDto=new DishDto();
            BeanUtils.copyProperties(dish,dishDto);//创造一个dishdto对象拷贝遍历出来的dish对象，并准备复制分类名称
            log.info("这里是=========================="+dishDto.getName());
            Long categoryId = dish.getCategoryId();//获取当前菜品的分类id
            Category category = categoryService.getById(categoryId);//找出该菜品所属于的分类
            if (category!=null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }else {
                dishDto.setCategoryName("暂无");
            }
            dtoList.add(dishDto);//更一个包含分类名的集合添加对象
        }
        pageDto.setRecords(dtoList);
        return R.success(pageDto);
    }
    //修改菜品前回显数据
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dto = dishService.getWithFlavor(id);
        return R.success(dto);
    }
    //修改菜品
    @PutMapping
    @CacheEvict(value = "dishCache",allEntries = true)
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);
//        //操作后，写上到该类型菜品缓存在数据中的key
//        String key="dish_"+dishDto.getCategoryId()+"_1";
//        //删除缓存
//        redisTemplate.delete(key);
        return R.success("操作成功");
    }
    //删除菜品
    @DeleteMapping
    @CacheEvict(value = "dishCache",allEntries = true)
    public R<String> delete(@RequestParam List<Long> ids){
        dishService.delete(ids);
//        //删除一些菜品后把菜品缓存所有分类都清理一遍
//        Set keys=redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);

        return R.success("删除成功");
    }
    //停售菜品
    @PostMapping("/status/{status}")
    @CacheEvict(value = "dishCache",allEntries = true)
    public R<String> updateStatus(@PathVariable Integer status,@RequestParam List<Long> ids){
        dishService.updateStatus(status,ids);
//        //停售一些菜品后把菜品缓存所有分类都清理一遍
//        Set<String> keys=redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);

        return R.success("操作成功");
    }
//    //查看菜品类别对应所含有的那些菜品
//    @GetMapping("/list")
//    public R<List<Dish>> list(Dish dish){
//        Long categoryId = dish.getCategoryId();
//        LambdaQueryWrapper<Dish> lqw=new LambdaQueryWrapper<>();
//        lqw.eq(categoryId!=null,Dish::getCategoryId,categoryId);
//        lqw.orderByDesc(Dish::getUpdateTime);
//        List<Dish> list = dishService.list(lqw);
//        return R.success(list);
//    }

    //查看菜品类别对应所含有的那些菜品
    @GetMapping("/list")
    @Cacheable(value = "dishCache",key = "#dish.categoryId+'_'+#dish.status")
    public R<List<DishDto>> list(Dish dish){
        List<DishDto> dtoList=null;
//        //手动设置缓存数据的动态key
//        String key="dish_"+dish.getCategoryId()+"_"+dish.getStatus();
//        //查询前先从换从数据里查询是否有数据
//        dtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
//        if (dtoList!=null){
//            return R.success(dtoList);
//        }
        //如果要则直接返回
        //如果没有便从数据库里面查询，并把查询出的数据存到redis中再返回
        Long categoryId = dish.getCategoryId();
        LambdaQueryWrapper<Dish> lqw=new LambdaQueryWrapper<>();
        lqw.eq(categoryId!=null,Dish::getCategoryId,categoryId);
        lqw.eq(Dish::getStatus,1);
        lqw.orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(lqw);
        dtoList=new ArrayStack<>();
        for (Dish d:list){
            //为移动端展示的菜品添加口味
            DishDto dishDto=new DishDto();
            BeanUtils.copyProperties(d,dishDto);
            LambdaQueryWrapper<DishFlavor> lqw2=new LambdaQueryWrapper<>();
            lqw2.eq(dish!=null,DishFlavor::getDishId,dishDto.getId());
            List<DishFlavor> flavors = dishFlavorService.list(lqw2);
            dishDto.setFlavors(flavors);
            dtoList.add(dishDto);
        }
//        //查询后把数据从redis
//        redisTemplate.opsForValue().set(key,dtoList,60, TimeUnit.MINUTES);
        return R.success(dtoList);
    }

}
